package com.infoland.afanmall.base.simple;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.StatusBarKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.model.story.adapter.StoryAdapter;
import com.infoland.afanmall.model.story.entity.StoryEntity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * 分页逻辑样例
 */

public class PageSimpleFragment extends Fragment {

    StoryAdapter thisAdapter; //适配器
    Unbinder unbinder;
    int pageNumber;
    int pageSize = CONST.STORY_FRAGMENT_PAGE_SIZE;
    boolean lastPage = false;
    @BindView(R.id.story_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.story_refresh_layout)
    SmartRefreshLayout storyRefreshLayout;
    boolean load = false; //执行 状态
    boolean ref = false;  //执行  状态
    boolean init = false; //执行 状态

    /*** main**/
    public void initData() {
        StatusBarKit.setPadding(getActivity(), mRecyclerView);
        initPageInfo();
        getStory();
        storyRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            LogKit.E("  storyRefreshLayout ", " storyRefreshLayout ");
            load = true;
            ref = false;
            init = false;
            startPage();
        });
        storyRefreshLayout.setOnRefreshListener(refreshLayout -> {
            LogKit.E("  storyRefreshLayout ", " storyRefreshLayout ");
            ref = true;
            load = false;
            init = false;
            lastPage = false;
            getStory();
        });
    }

    /*** 开始查询**/
    private void getStory() {
        JSONObject para = getPagePara();
        new OkHttpKit().send(
                response200 -> {
                    StoryEntity storyEntity = JSON.parseObject(response200, StoryEntity.class);
                    if (storyEntity.isSuccess()) {
                        StoryEntity.ObjectBean object = storyEntity.getObject();
                        setPageInfo(object);
                        if (load) {
                            loadData(object.getList());
                        } else if (ref) {
                            refData(object.getList());
                        } else if (init) {
                            setAdapter(object.getList());
                        } else {
                            refData(object.getList());
                        }
                    } else {

                    }
                },
                error401 -> {
                },
                error -> {
                }
        ).post(CONST.STORY_LIST, para, getActivity());
    }

    /*** 设置适配器**/
    private void setAdapter(List<StoryEntity.ObjectBean.ListBean> list) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        thisAdapter = new StoryAdapter(list, Objects.requireNonNull(getActivity()).getApplicationContext(), mRecyclerView, StatusBarKit.getStatusBarHeight(getActivity()));
        mRecyclerView.setAdapter(thisAdapter);
    }

    /*** 初始化分页参数 **/
    private void initPageInfo() {
        init = true;
        ref = false;
        load = false;
        pageNumber = 1;
        pageSize = CONST.STORY_FRAGMENT_PAGE_SIZE;
    }

    /*** 加载数据**/
    private void loadData(List<StoryEntity.ObjectBean.ListBean> list) {
        thisAdapter.addData(list);
        thisAdapter.loadMoreComplete();
        storyRefreshLayout.finishLoadMore();
        LogKit.E(" loadData  ", "加载数据  ");
    }

    /*** 刷新数据 **/
    private void refData(List<StoryEntity.ObjectBean.ListBean> list) {
        thisAdapter.setNewData(list);
        thisAdapter.loadMoreComplete();
        storyRefreshLayout.finishRefresh();
        LogKit.E(" refData  ", "刷新数据  " + list.size());
    }

    /*** 检查当前分页,然后开始查询 **/
    private void startPage() {
        if (lastPage) {
            storyRefreshLayout.finishLoadMore();
            ToastUtils.showShort("已经是最后一页了");
        } else {
            pageNumber += 1;
            getStory();
        }
    }

    /*** 设置分页参数（请求数据之后）**/
    private void setPageInfo(StoryEntity.ObjectBean object) {
        LogKit.E(" setPageInfo  ", "设置分页参数  ");
        pageNumber = object.getPageNumber();
        pageSize = object.getPageSize();
        lastPage = object.isLastPage();
    }

    /*** 获取分页参数 **/
    private JSONObject getPagePara() {
        JSONObject para = new JSONObject();
        para.put("pageNumber", 1);
        para.put("pageSize", CONST.STORY_FRAGMENT_PAGE_SIZE);
        return para;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.story_fragment, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}